package com.woniuxy.web.exception;



import com.woniuxy.core.exception.WoniuxyException;
import com.woniuxy.core.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Component
@RestControllerAdvice
@Slf4j
public class GlobleExceptionHandler {

    /**
     * 参数校验异常统一处理
     * @param e 参数异常对象
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result argumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        BindingResult br = e.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        for (FieldError error : br.getFieldErrors()) {
            errorMessage.append(error.getDefaultMessage()).append("; ");
        }
        log.error("参数校验失败:"+errorMessage.toString(),e);
        return Result.fail(500,errorMessage.toString());
    }

    @ExceptionHandler(WoniuxyException.class)
    public Result woniuxyExceptionHandler(WoniuxyException e){
        log.error("出现异常:{}",e);
        return Result.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    public Result throwableHandler(Throwable e){
        log.error("出现异常：{}",e);
        e.printStackTrace();
        return Result.fail(500,"系统异常");
    }
}
